<template>
  <div>
    <van-cell-group>
      <van-field v-model="value2" :label="label" :placeholder="placeholder">
        <template #button>
          <van-button
            type="default"
            :disabled="verifyBtnDisabled"
            @click.native="handleVerifyCode"
          >
            {{ verifyBtnTitle }}
          </van-button>
        </template>
      </van-field>
    </van-cell-group>
  </div>
</template>

<script>
import { Toast } from 'vant'

export default {
  name: 'SmsCode',
  components: {},
  directives: {},
  filters: {},
  props: {
    value: { type: String, default: '' },
    mobile: { type: String, default: '' },
    label: { type: String, default: '' },
    title: { type: String, default: '获取验证码' },
    placeholder: { type: String, default: '输入验证码' }
  },

  data() {
    return {
      verifyBtnTitle: this.title,
      verifyBtnDisabled: false
    }
  },
  computed: {
    value2: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },

  watch: {},

  async created() {
    //
  },

  methods: {
    async handleVerifyCode() {
      console.log(this.mobile)
      if (this.validatePhone(this.mobile)) {
        this.validateBtn()
        this.$emit('click')
      }
    },

    validatePhone(mobile) {
      // 判断输入的手机号是否合法
      if (!mobile) {
        Toast('手机号码不能为空')

        // return false
      } else if (!/^1[345678]\d{9}$/.test(mobile)) {
        Toast('请输入正确的手机号')
      } else {
        // this.errorMessage = {}
        return true
      }
    },

    validateBtn() {
      // 倒计时
      let time = 60
      const timer = setInterval(() => {
        if (time === 0) {
          clearInterval(timer)
          this.verifyBtnDisabled = false
          this.verifyBtnTitle = this.title
        } else {
          this.verifyBtnTitle = time + '秒后重试'
          this.verifyBtnDisabled = true
          time--
        }
      }, 100)
    }
  }
}
</script>

<style type="text/css"></style>
